package com.aw.baselib.util

import android.content.Context
import android.content.pm.PackageManager
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
 * Created by hzw
 */
object AwVersionUtil {
    /**
     * 版本号对比
     *
     * @param oldVersion
     * @param newVersion
     * @return error : 返回-2 既传入版本号格式有误
     * oldVersion > newVersion  return -1
     * oldVersion = newVersion  return 0
     * oldVersion < newVersion  return 1
     */
    fun compareVersions(oldVersion: String, newVersion: String): Int {
        //返回结果: -2 ,-1 ,0 ,1
        var oldVersion = oldVersion
        var newVersion = newVersion
        var result = 0
        val matchStr = "[0-9]+(\\.[0-9]+)*"
        oldVersion = oldVersion.trim { it <= ' ' }
        newVersion = newVersion.trim { it <= ' ' }
        //非版本号格式,返回error
        if (!oldVersion.matches(matchStr.toRegex()) || !newVersion.matches(matchStr.toRegex())) {
            return -2
        }
        val oldVs = oldVersion.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        val newVs = newVersion.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        val oldLen = oldVs.size
        val newLen = newVs.size
        val len = if (oldLen > newLen) oldLen else newLen
        for (i in 0 until len) {
            if (i < oldLen && i < newLen) {
                val o = oldVs[i].toInt()
                val n = newVs[i].toInt()
                if (o > n) {
                    result = -1
                    break
                } else if (o < n) {
                    result = 1
                    break
                }
            } else {
                if (oldLen > newLen) {
                    for (j in i until oldLen) {
                        if (oldVs[j].toInt() > 0) {
                            result = -1
                        }
                    }
                    break
                } else if (oldLen < newLen) {
                    for (j in i until newLen) {
                        if (newVs[j].toInt() > 0) {
                            result = 1
                        }
                    }
                    break
                }
            }
        }
        return result
    }

    fun sHA1(context: Context): String? {
        try {
            val info = context.packageManager.getPackageInfo(
                context.packageName, PackageManager.GET_SIGNATURES
            )
            val cert = info.signatures!![0].toByteArray()
            val md = MessageDigest.getInstance("SHA1")
            val publicKey = md.digest(cert)
            val hexString = StringBuffer()
            for (i in publicKey.indices) {
                val appendString = Integer.toHexString(0xFF and publicKey[i].toInt())
                    .uppercase()
                if (appendString.length == 1) {
                    hexString.append("0")
                }
                hexString.append(appendString)
                hexString.append(":")
            }
            val result = hexString.toString()
            return result.substring(0, result.length - 1)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    fun getVersion(context: Context): String {
        return try {
            val manager = context.packageManager
            val info = manager.getPackageInfo(context.packageName, 0)
            val version = info.versionName
            "v$version"
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }
}